package com.guaoran.study.future;

import java.util.concurrent.*;

/**
 * @Desc： feture demo
 * @Auth gucheng
 * @Date 2020/10/30 下午6:20.
 */
public class FutureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executor =
                Executors.newFixedThreadPool(1);
        // 创建Result对象r
        Result r = new Result();
        r.setAAA("aa");
        // 提交任务
        Future<Result> future = executor.submit(new Task(r), r);
        Result fr = future.get();
        // 下面等式成立
        System.out.println(fr==r);
        System.out.println(fr.getAAA()=="aa");
        System.out.println(fr.getXXX()=="x");
        executor.shutdown();



        // 创建FutureTask
        FutureTask<Integer> futureTask
                = new FutureTask<>(()-> 1+2);
        // 创建线程池
        ExecutorService es =
                Executors.newCachedThreadPool();
        // 提交FutureTask
        es.submit(futureTask);
        // 获取计算结果
        Integer result = futureTask.get();
        System.out.println(result);
        es.shutdown();


// 创建FutureTask
        FutureTask<Integer> futureTask2
                = new FutureTask<>(()-> 1+2);
// 创建并启动线程
        Thread T1 = new Thread(futureTask2);
        T1.start();
// 获取计算结果
        Integer result2 = futureTask2.get();
        System.out.println(result2);
    }
    static class Task implements Runnable{
        Result r;
        //通过构造函数传入result
        Task(Result r){
            this.r = r;
        }
        public void run() {
            //可以操作result
            String a = r.getAAA();
            r.setXXX("x");
        }
    }
    static class  Result {
        String AAA;
        String XXX;

        public String getAAA() {
            return AAA;
        }

        public void setAAA(String AAA) {
            this.AAA = AAA;
        }

        public String getXXX() {
            return XXX;
        }

        public void setXXX(String XXX) {
            this.XXX = XXX;
        }

        public Result() {
        }
    }

}
